<?php

/**
 * @author extintor
 * @copyright 2012
 */

class indexer{
    private $db;
    private $iu;
    
    public function __construct(){
        $this->db=new dbConnection();    
        $this->iu=new indexUtil();    
    }
    
    public function indexDocument($document, $text){
        $idDocument=$this->existsDocument($document);
        if($idDocument>0){
           $this->db->exec("delete from documentword where id_document=$idDocument");  
           echo "borro\n";
        }else{
           $idDocument=$this->getDocumentId($document);
        }
        echo "Longitud del documento: ".strlen($text)." caracteres\n";
        $words=$this->iu->getUniqueWords($text);
        //print_r($words);
        $sql="insert into documentword (id_document, id_word) values ";
        $ll="";
        foreach($words as $word){
           if (substr($word,0,1)!=$ll){
              $ll=substr($word,0,1);
              echo $ll;
           }
           $idWord=$this->getWordId($word);
           $sql.="($idDocument,$idWord),";
        }
        echo "\n";
        $sql=substr($sql,0,-1);
        $this->db->exec($sql);
    }
    
    public function existsDocument($document){
        $sql="select id_document from document where document='$document'";
        $res=$this->db->query($sql)->fetchAll();
        if ($res){
           return $res[0][0];
        }else{
           return 0;
        }    
    }    
    
    public function getDocumentId($document){
        $idDocument=$this->existsDocument($document);
        if ($idDocument>0){
           return $idDocument;
        }else{
           $sql="insert into document (document) values ('$document');";
           $this->db->exec($sql);
           return $this->getDocumentId($document); 
        }
    }
    
    public function getLemmaId($lemma){
        $sql="select id_lemma from lemma where lemma='$lemma'";
        $res=$this->db->query($sql)->fetchAll();
        if ($res){
           return $res[0][0];
        }else{
           $sql="insert into lemma (lemma) values ('$lemma');";
           $this->db->exec($sql);
           return $this->getLemmaId($lemma); 
        }
    }
    
    public function getWordId($word){
        $sql="select id_word from word where word='$word'";
        $res=$this->db->query($sql)->fetchAll();
        if ($res){
           return $res[0][0];
        }else{
           $lemmaId=$this->getLemmaId($this->iu->stemm($word)); 
           $sql="insert into word (word, id_lemma) values ('$word',$lemmaId);";
           $this->db->exec($sql);
           return $this->getWordId($word); 
        }
    }

}




?>